package proxy;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class CustomerProxy {
    public static Object getProxy(final Class cs, final String host, final int port){
        return Proxy.newProxyInstance(cs.getClassLoader(), new Class[]{cs}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //System.out.println("151115"+method);
                Socket socket = new Socket(host, port);
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                out.writeUTF(cs.getSimpleName());
                //System.out.println("clz.getSimpleName()"+clz.getSimpleName());
                out.writeUTF(method.getName());
                //System.out.println("method.getName()"+method.getName());
                out.writeObject(method.getParameterTypes());
                //System.out.println("method.getParameterTypes()"+method.getParameterTypes());
                out.writeObject(args);
//                System.out.println("args"+(Student)args[0]);
                Object o = in.readObject();
                socket.close();
                return o;
            }
        });
    }
}
